package com.hspedu.set_;

import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Objects;

/**
 * @Author Stringzhua
 * @Date 2024/3/12 18:57
 * description:
 * Car类(属性:name,price)
 * 如果name和price相同
 * 则认为是相同元素,就不能添加
 *
 * 这里通过重写hashCode()和equals()解决重复的问题
 */
@SuppressWarnings("all")
public class LinkedHashSetExercise {
    public static void main(String[] args) {
        LinkedHashSet linkedHashSet = new LinkedHashSet();
        linkedHashSet.add(new Car("奥拓", 1000));
        //和下面的奥迪是不同的对象,哈希值不同,但是这里只能创建一个奥迪对象,所以
        //通过重写hashCode()和equals()去解决相同元素的问题
        linkedHashSet.add(new Car("奥迪", 300000));
        linkedHashSet.add(new Car("法拉利",10000000));
        linkedHashSet.add(new Car("奥迪", 300000));
        linkedHashSet.add(new Car("保时捷",70000000));
        linkedHashSet.add(new Car("奥迪",300000));

        System.out.println("linkedHashSet = " + linkedHashSet);

        Iterator iterator = linkedHashSet.iterator();
        while (iterator.hasNext()) {
            Object next =  iterator.next();
            System.out.println("next = " + next);
        }

        for (Object o :linkedHashSet) {
            System.out.println("o = " + o);
        }

    }
}

class Car {
    private String name;
    private double price;

    public Car(String name, double price) {
        this.name = name;
        this.price = price;
    }
    /*
    * 重写equals方法和hashCode
    * 当name和price相同时,就返回相同的hashCode值,equals返回t
    * */

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Car car = (Car) o;
        return Double.compare(car.price, price) == 0 &&
                Objects.equals(name, car.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, price);
    }

    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}